package com.djdg.foodies.admin.base.interceptor;

import com.djdg.foodies.admin.base.annotation.Secured;
import com.djdg.foodies.admin.base.exception.UnAuthorizedException;
import com.djdg.foodies.common.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 登录信息拦截器
 * @Auther Demon
 * @Date 2018/1/4 0004 23:11 星期四
 */
@Component
public class SecuredInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(SecuredInterceptor.class);

    private static final String TOKEN = "token";
    private static final String ACCOUNT_ID = "accountId";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
        if (o instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            Secured secured = handlerMethod.getMethodAnnotation(Secured.class);
            if (secured != null) {
                String token = request.getHeader(TOKEN);
                logger.info("SecuredInterceptor > header token = {}", token);
                if(StringUtils.isBlank(token)) {
                    throw new UnAuthorizedException();
                }

                String tokenKey = RedisKeyUtil.getUserTokenKey(token);
                if(!stringRedisTemplate.hasKey(tokenKey)) {
                    throw new UnAuthorizedException();
                }
                Long accountId = Long.parseLong(stringRedisTemplate.opsForValue().get(tokenKey));
                request.getSession().removeAttribute(ACCOUNT_ID);
                request.getSession().setAttribute(ACCOUNT_ID, accountId);
                logger.info("SecuredInterceptor > accountId set in session : {} = {}", token, accountId);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        /*httpServletRequest.getSession().removeAttribute(USER_ID);
        logger.info("SecuredInterceptor > request finished, remove userId in session.");*/
    }
}
